/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.biz.service.impl;

import me.zhengjie.modules.biz.domain.HazardousChemicalsTotal;
import me.zhengjie.modules.biz.domain.Project;
import me.zhengjie.modules.biz.domain.ProjectHazardousChemicals;
import me.zhengjie.modules.biz.repository.HazardousChemicalsTotalRepository;
import me.zhengjie.modules.biz.repository.ProjectHazardousChemicalRepository;
import me.zhengjie.modules.biz.service.dto.HazardousChemicalsTotalDto;
import me.zhengjie.modules.biz.service.mapstruct.HazardousChemicalsTotalMapper;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.ProjectRepository;
import me.zhengjie.modules.biz.service.ProjectService;
import me.zhengjie.modules.biz.service.dto.ProjectDto;
import me.zhengjie.modules.biz.service.dto.ProjectQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.ProjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Admin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-03-23
 **/
@Service
@RequiredArgsConstructor
public class ProjectServiceImpl implements ProjectService {

    private final ProjectRepository projectRepository;
    private final ProjectMapper projectMapper;
    private final HazardousChemicalsTotalRepository hazardousChemicalsTotalRepository;
    private final HazardousChemicalsTotalMapper hazardousChemicalsTotalMapper;
    private final ProjectHazardousChemicalRepository projectHazardousChemicalRepository;

    @Override
    public Map<String, Object> queryAll(ProjectQueryCriteria criteria, Pageable pageable) {
        Page<Project> page = projectRepository.findAll(
                (root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder),
                pageable
        );

        Page<ProjectDto> dto = page.map(projectMapper::toDto);
        List<ProjectDto> projectDtos = dto.getContent();
        for (ProjectDto projectDto : projectDtos) {
            List<Map<String, Object>> data = projectHazardousChemicalRepository.findByProjectId(projectDto.getId());
            projectDto.setProjectHazardousChemicals(data);

            List<Integer> totalIds = new ArrayList<>();
//            for (ProjectHazardousChemicals tmpProjectHazardousChemicals:data
//                 ) {
//                totalIds.add(tmpProjectHazardousChemicals.getTotalId());
//            }
//            projectDto.setTotalIds(totalIds);

//            List<HazardousChemicalsTotalDto> hazardousChemicalsTotalDtoList =
//                    hazardousChemicalsTotalMapper.toDto(
//                            hazardousChemicalsTotalRepository.findByIds(projectDto.getId())
//                    );
//            for (HazardousChemicalsTotalDto hazardousChemicalsTotalDto : hazardousChemicalsTotalDtoList) {
//                if (hazardousChemicalsTotalDto.getCountType() == 1) {
//                    hazardousChemicalsTotalDto.setDesc(hazardousChemicalsTotalDto.getName().concat(" ").concat(String.valueOf(hazardousChemicalsTotalDto.getAmount())).concat("(ml)"));
//                } else {
//                    hazardousChemicalsTotalDto.setDesc(hazardousChemicalsTotalDto.getName().concat(" ").concat(String.valueOf(hazardousChemicalsTotalDto.getAmount())).concat("(g)"));
//                }
//            }
//            projectDto.setHazardousChemicalsTotalsDtos(hazardousChemicalsTotalDtoList);
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public List<ProjectDto> queryAll(ProjectQueryCriteria criteria) {

        return projectMapper.toDto(projectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public ProjectDto findById(Integer id) {
        Project project = projectRepository.findById(id).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", id);
        return projectMapper.toDto(project);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectDto create(Project resources) {
        return projectMapper.toDto(projectRepository.save(resources)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Project resources) {
        Project project = projectRepository.findById(resources.getId()).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", resources.getId());
        project.copy(resources);
        project.setDesc(resources.getDesc());
        projectRepository.save(project);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            projectRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ProjectDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectDto project : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("项目名称", project.getName());
            map.put("项目描写", project.getDesc());
            map.put("创建人", project.getCreatorId());
            map.put(" createdAt", project.getCreatedAt());
            map.put(" updatedAt", project.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String, Object> findUserProjectList(Long id) {
        List<Project> projects = projectRepository.findProjectsByUserId(Math.toIntExact(id));
//        for (Project p:projects) {
//            p.setId(projectRepository.findId(p.getName(),p.getDesc()));
//        }
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("data", projects);
        return stringObjectMap;

    }

    @Override
    public List<HazardousChemicalsTotalDto> queryProjectData(HttpServletRequest request) {
        int projectId = Integer.parseInt(request.getParameter("id"));
        String cabinetIdsString = request.getParameter("cabinetIds");

        String[] cabinetIdsArr = cabinetIdsString.split(",");

        int[] cabinetIds = new int[cabinetIdsArr.length];

        for (int i = 0; i < cabinetIdsArr.length; i++) {
            cabinetIds[i] = Integer.parseInt(cabinetIdsArr[i]);
        }

        //查找不需要审批的试剂信息
        List<HazardousChemicalsTotal> hazardousChemicalsTotals;
        if (cabinetIds.length == 0) {
            hazardousChemicalsTotals = hazardousChemicalsTotalRepository
                    .findByIdsNotApply(projectId);
        } else {
            hazardousChemicalsTotals = hazardousChemicalsTotalRepository
                    .findByIdsNotApplyTypeCabinet(projectId, cabinetIds);
        }

        return hazardousChemicalsTotalMapper.toDto(hazardousChemicalsTotals);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindHazardous(Integer projectId, Integer[] totalIds) {
        projectHazardousChemicalRepository.deleteByProjectId(projectId);
        List<ProjectHazardousChemicals> projectHazardousChemicals = new ArrayList<>();
        for (int i = 0; i < totalIds.length; i++) {
            HazardousChemicalsTotal total = hazardousChemicalsTotalRepository.getById(totalIds[i]);
            ProjectHazardousChemicals tmpData = new ProjectHazardousChemicals();
            tmpData.setProjectId(projectId);
            tmpData.setHctId(totalIds[i]);
            projectHazardousChemicals.add(tmpData);
        }

        projectHazardousChemicalRepository.saveAll(projectHazardousChemicals);
    }
}
